/**
 * SpringMVC restful 风格
 * 购买过程 控制器，控制关于购物车,订单，支付的一些业务逻辑操作
 * @author WangXinLei
 * @date 2014-09-12
 */
package com.chnbst.bstyun.controller.user;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.CreateOrderNum;
import com.chnbst.bstyun.core.common.DateUtil;
import com.chnbst.bstyun.core.common.ReadProperties;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.eos.CreateNum;
import com.chnbst.bstyun.eos.Eos;
import com.chnbst.bstyun.model.pojo.Cashflow;
import com.chnbst.bstyun.model.pojo.Deal;
import com.chnbst.bstyun.model.pojo.Meal;
import com.chnbst.bstyun.model.pojo.MealFee;
import com.chnbst.bstyun.model.pojo.MealProduct;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.Payment;
import com.chnbst.bstyun.model.pojo.Product;
import com.chnbst.bstyun.model.pojo.ProductFee;
import com.chnbst.bstyun.model.pojo.ShoppingCart;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.pojo.Voucher;
import com.chnbst.bstyun.model.vo.OrderVo;
import com.chnbst.bstyun.model.vo.ShoppingCartVo;
import com.chnbst.bstyun.service.CashflowService;
import com.chnbst.bstyun.service.DealService;
import com.chnbst.bstyun.service.MealFeeService;
import com.chnbst.bstyun.service.MealProductService;
import com.chnbst.bstyun.service.MealService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.PaymentService;
import com.chnbst.bstyun.service.ProductFeeService;
import com.chnbst.bstyun.service.ProductService;
import com.chnbst.bstyun.service.ShoppingCartService;
import com.chnbst.bstyun.service.UserService;
import com.chnbst.bstyun.service.VoucherService;
import com.chnbst.mail.EmailUtil;

/**
 * 控制器注解 请求映射注解 controller 代表类是控制器 restcontroller 代表类是控制器， 所有的方法 都是ajax方法
 */
@Controller
@RequestMapping("/buy")
public class BuyProcessController {
	/**
	 * 注入 业务逻辑层
	 */
	@Autowired 
	private ShoppingCartService shoppingCartService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private MealService mealService;
	@Autowired
	private MealFeeService mealFeeService;
	@Autowired
	private ProductService productService;
	@Autowired
	private ProductFeeService productFeeService;
	@Autowired
	private MealProductService mealProductService;
	@Autowired
	private UserService userService;
	@Autowired 
	private DealService dealService;
	@Autowired
	private VoucherService voucherService;
	@Autowired
	private CashflowService cashflowService;
	@Autowired 
	private Eos eos;
	@Autowired
	private CreateNum createNum;
	@Autowired
	private ReadProperties readProperties;
	@Autowired PaymentService paymentService;
	
	/**
	 * ajax请求 查询用户是否免费使用过
	 * @param request
	 * @return boolean
	 */
	@RequestMapping(value = "/checkBuy", method = RequestMethod.POST)
	@ResponseBody
	public boolean checkBuy(HttpServletRequest request) throws Exception {
		boolean isBuy = false;
		User user = (User)request.getSession().getAttribute("userInfo");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", user.getUserId());
		map.put("overTime", new Date());
		map.put("isYun", user.getIsYun());
		user = userService.selectUserByConditons(map);
		if(user != null) {
			isBuy = true;
		}
		return isBuy;
	}
	
	/**
	 * @return 加入购物车
	 * @throws Exception
	 */
	@RequestMapping(value = "/shoppingCart/add", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addShoppingCart(Integer proMealId,String pmStatus,
		Integer useLife,Integer userNum,Double proMealPrice,HttpServletRequest request) throws Exception {
		User user = (User)request.getSession().getAttribute("userInfo");
		
		ShoppingCart shoppingCart = new ShoppingCart();
		
		if(useLife == 0) {
			proMealPrice = 0.00;
		}else if(useLife == -1) {
			//套餐
			MealFee mf = mealFeeService.selectMealFeeByMealId(proMealId);
			proMealPrice = (mf.getPrice()/mf.getUserNum())*userNum;
		}else {
			if("0".equals(pmStatus)) {
				//套餐
				MealFee mf = mealFeeService.selectMealFeeByMealId(proMealId);
				proMealPrice = (mf.getPrice()/mf.getUserNum()/mf.getUserYear())*userNum*useLife;
			}else {
				//产品
				ProductFee pf = productFeeService.selectProductFeeByProductId(proMealId);
				proMealPrice = (pf.getProductPrice()/pf.getUserNum()/pf.getUseYear())*userNum*useLife;
			}
		}
		
		shoppingCart.setAddTime(new Date());
		shoppingCart.setIsDelete("0");
		shoppingCart.setIsFree(0);
		shoppingCart.setPmStatus(pmStatus);
		shoppingCart.setProMealNum(1);
		shoppingCart.setProMealId(proMealId);
		shoppingCart.setProMealPrice(proMealPrice);
		shoppingCart.setUseLife(String.valueOf(useLife));
		shoppingCart.setUserId(user.getUserId());
		shoppingCart.setUserNum(userNum);
		
		boolean isSuccess = shoppingCartService.insertShoppingCart(shoppingCart);
		
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>)request.getSession().getAttribute("cartInfo");
		
		if(isSuccess) {
			map.put("sumNum", Integer.valueOf(map.get("sumNum").toString())+1);
			map.put("sumPrice", Double.valueOf(map.get("sumPrice").toString())+proMealPrice);
			
			request.getSession().setAttribute("cartInfo",map);
			
		}
		
		map.put("isSuccess", isSuccess);
		return map;
	}

	/**
	 * @return 购物车页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/shoppingCart", method = RequestMethod.GET)
	public ModelAndView shoppingCart(HttpServletRequest request) throws Exception {
		
		User user = (User)request.getSession().getAttribute("userInfo");
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("buy/shopping-cart");
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId",user.getUserId());
		
		List<ShoppingCartVo> scList = shoppingCartService.selectShoppingCartVosByUserId(map);
		modelAndView.addObject("scList",scList);
		
		return modelAndView;
	}
	
	/**
	 * get请求    删除购物车单条信息
	 */
	@RequestMapping(value="/deleteShoppingCartByShoppingCartId/{shoppingCartId}",method=RequestMethod.GET)
	@ResponseBody
	public ModelAndView deleteShoppingCartByShoppingCartId(@PathVariable Integer shoppingCartId,HttpServletRequest request){
		/**
		 * 删除 购物车 单条信息
		 */
		ShoppingCart shoppingCart = shoppingCartService.selectShoppingCartByShoppingCartId(shoppingCartId);
		shoppingCart.setIsDelete("-1");
		
		boolean b = shoppingCartService.updateShoppingCart(shoppingCart);
		
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>)request.getSession().getAttribute("cartInfo");
		
		if(b) {
			map.put("sumNum", Integer.valueOf(map.get("sumNum").toString())-1);
			map.put("sumPrice", Double.valueOf(map.get("sumPrice").toString())-shoppingCart.getProMealPrice());
			
			request.getSession().setAttribute("cartInfo",map);
		}
		
		ModelAndView mav = new ModelAndView();
		
		mav.setViewName("buy/shopping-cart");
		mav.addObject("data", b);
		return mav;
	}
	
	/**
	 * get请求    批量删除购物车信息
	 */
	@RequestMapping(value="/deleteShoppingCartsByShoppingCartId/{shoppingCartList}",method=RequestMethod.GET)
	@ResponseBody
	public ModelAndView deleteShoppingCartsByShoppingCartId(@PathVariable String shoppingCartList,HttpServletRequest request){
		/**
		 * 批量删除 购物车 信息
		 */
		boolean b = false;
		String[] a = shoppingCartList.split(",");
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>)request.getSession().getAttribute("cartInfo");
		for(int i=0;i<a.length;i++){
			ShoppingCart shoppingCart = shoppingCartService.selectShoppingCartByShoppingCartId(Integer.parseInt(a[i]));
			shoppingCart.setIsDelete("-1");
			
			b = shoppingCartService.updateShoppingCart(shoppingCart);
			if(b) {
				map.put("sumNum", Integer.valueOf(map.get("sumNum").toString())-1);
				map.put("sumPrice", Double.valueOf(map.get("sumPrice").toString())-shoppingCart.getProMealPrice());
			}
		}
		
		request.getSession().setAttribute("cartInfo",map);
		ModelAndView mav = new ModelAndView();
		mav.setViewName("buy/shopping-cart");
		
		if(b == true) mav.addObject("data", "success");
		else mav.addObject("data", "fail");
		
		return mav;
	}
	
	/**
	 * @return 确认订单 时  判断  查询指定用户是否有套餐
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value="/haveMealByUserId",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> haveMealByUserId(HttpServletRequest request){
		User user = (User)request.getSession().getAttribute("userInfo");
		
		Map<String, Object> _map = new HashMap<String, Object>();
		_map.put("userId",user.getUserId());
		_map.put("isYun",user.getIsYun());
		_map.put("sortField","o.pay_time");
		_map.put("sortOrder","desc");
		_map.put("groupField","t.user_id,t.meal_id");
		
		List<OrderVo> orderVoList = orderService.selectOrderByCondition(_map);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("start", 0);
		map.put("pageSize", Integer.MAX_VALUE);
		map.put("sortField", "p.product_id");
		map.put("sortOrder", "asc");
		List<Product> proList = productService.selectProducts(map);
		
		request.getSession().setAttribute("userMealInfo", orderVoList);
		request.getSession().setAttribute("proList", proList);
		
		map.put("isSuccess",true);
		map.put("orderVoList",orderVoList);
		map.put("proList",proList);
		
		return map;
	}
	
	/**
	 * @return 点击去购买时判断该产品是否曾经免费添加到套餐 
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value="/selectOrderByIsFree",method=RequestMethod.POST)
	@ResponseBody
	public boolean selectOrderByIsFree(HttpServletRequest request,String userId,String mealId,String newProId,Double proMealPrice){
		/*Integer isFree = 0;
		if(proMealPrice == 0.0) isFree = 1;*/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId",userId);
		map.put("mealId",mealId);
		map.put("newProId",newProId);
		map.put("sortField", "pay_time");
		map.put("sortOrder", "desc");
		/*map.put("isFree", isFree);*/
		
		List<Order> orderList = orderService.selectOrderByIsFree(map);
		
		if(orderList != null && orderList.size() > 0 ){
			return false;
		}else return true;
	}
	
	/**
	 * @return 购物车数据到核对产品订单页面
	 * @throws Exception 
	 * @throws NumberFormatException 
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value="/cartToCheck",method=RequestMethod.POST)
	@ResponseBody
	public boolean cartToCheck(HttpServletRequest request ,String _sc,String productId,Integer orderId) throws NumberFormatException, Exception{
		
		ObjectMapper objectMapper = new ObjectMapper();
		ShoppingCartVo arr = null;
		try {
			arr = objectMapper.readValue(_sc, ShoppingCartVo.class);
	    } catch (JsonParseException e) {
	        e.printStackTrace();
	    } catch (JsonMappingException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
		
		//套餐
		if("0".equals(productId)) {
			String useLife = arr.getUseLife();
			if(arr.getUseLife().endsWith("-1")) {
				useLife = "1";
			}
			MealFee mf = mealFeeService.selectMealFeeByMealId(arr.getProMealId());
			
			Integer mfUseYear = mf.getUserYear();
			if(mfUseYear == -1) {
				mfUseYear = 1;
			}
			Double mealPrice = (mf.getPrice()/mfUseYear/mf.getUserNum())*Integer.parseInt(useLife)*arr.getUserNum();
			arr.setProMealPrice(mealPrice);
			if(mealPrice == 0.0 || Integer.parseInt(useLife) == 0 || arr.getUserNum() == 0) {
				arr.setPrice(0.00);
			}else{
				arr.setPrice(mealPrice/Integer.parseInt(useLife)/arr.getUserNum());
			}
		}else {
			//根据套餐Id和用户Id查找最近一条订单记录
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("mealId", arr.getProMealId());
			map.put("userId", arr.getUserId());
			map.put("sortField", "pay_time");
			map.put("sortOrder", "desc");
			
			Order order = orderService.selectOrderByMealIdAndProductId(map);
			
			//套餐的使用年限和使用人数
			String orderUseLife = order.getUseLife();
			Integer orderUserNum = order.getUserNum();
			
			//所选择产品的使用年限和使用人数
			String arrUseLife = arr.getUseLife();
			Integer arrUserNum = arr.getUserNum();
			
			//设置默认值为0
			Double proPrice = 0.00;
			Integer userNum = 0;
			String _toDate = "";
			
			//人数计算
			if(arrUserNum > orderUserNum){
				userNum = orderUserNum;
			}else{
				userNum = arrUserNum;
			}
			arr.setUserNum(userNum);
			
			//试用   年限及价格计算
			if(arrUseLife.equals("0")){
				proPrice = 0.00;
				_toDate = DateUtil.getMonth("getOverTime", new Date(),order.getOverTime());
				Integer _day = DateUtil.getDateAndTodayDiffer(new java.sql.Date(order.getOverTime().getTime()));
				if(_day <= 20){
					arr.setUseLife(_toDate);
					arr.setPrice(0.00);
					arr.setEndTime(order.getOverTime());
				}else{
					arr.setUseLife("20天");
					arr.setPrice(0.00);
					arr.setEndTime(SignUtil.getOvertime(5, +20,new Date()));
				}
			}else{
				//购买   年限及价格计算
				
				ProductFee pf = productFeeService.selectProductFeeByProductId(Integer.valueOf(productId));
				
				if(orderUseLife.equals("0")){
					_toDate = DateUtil.getMonth("getOverTime", new Date(),order.getOverTime());
					Integer _day = DateUtil.getDateAndTodayDiffer(new java.sql.Date(order.getOverTime().getTime()));
					if(_day <= 20){
						arr.setUseLife(_toDate);
						proPrice = 0.00;
						arr.setPrice(0.00);
						arr.setEndTime(order.getOverTime());
					}else{
						arr.setUseLife("20天");
						proPrice = 0.00;
						arr.setPrice(0.00);
						arr.setEndTime(SignUtil.getOvertime(5, +20,new Date()));
					}
				}else {
					//计算所选择的截止日期
					Date endTime = SignUtil.getOvertime(1, +Integer.valueOf(arrUseLife),new Date());
					//还有多长时间到期  年月日
					_toDate = DateUtil.getMonth("getOverTime", new Date(),order.getOverTime());
					Integer _month = Integer.valueOf(DateUtil.getMonth("getMonth", new Date(),order.getOverTime()));
					
					if(endTime.getTime() <= order.getOverTime().getTime()){
						arr.setUseLife(arrUseLife+'年');
						proPrice = pf.getProductPrice()/pf.getUserNum()/pf.getUseYear()*Integer.valueOf(arrUseLife)*arr.getUserNum();
						arr.setPrice(pf.getProductPrice()/pf.getUserNum()/pf.getUseYear());
						arr.setEndTime(endTime);
					}else{
						arr.setUseLife(_toDate);
						proPrice = pf.getProductPrice()/pf.getUserNum()/pf.getUseYear()/12*_month*arr.getUserNum();
						arr.setPrice(pf.getProductPrice()/pf.getUserNum()/pf.getUseYear());
						arr.setEndTime(order.getOverTime());
					}
				}
			}
			arr.setProMealPrice(proPrice);
		} 
		
		request.getSession().setAttribute("sc", arr);
		request.getSession().setAttribute("productId", productId);
		
		return true;
	}
	
	/**
	 * @return 核对产品订单页面
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkOrders", method = RequestMethod.GET)
	public ModelAndView checkOrders(HttpServletRequest request) throws UnsupportedEncodingException{
		ShoppingCartVo sc = (ShoppingCartVo) request.getSession().getAttribute("sc");
		String productId = (String) request.getSession().getAttribute("productId");
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("buy/check-orders");
		modelAndView.addObject("_sc",sc);
		modelAndView.addObject("productId",productId);
		return modelAndView;
	}
	
	/**
	 * @return 核对产品订单到提交订单页面    免费产品购买  
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value="/checkToSubmit",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkToSubmit(HttpServletRequest request ,String orderList,String isPay,String productId) throws Exception{
		
		User user = (User)request.getSession().getAttribute("userInfo");
		String orderNum = CreateOrderNum.getOrderNum(user.getUserId());
		String EOSresult = null;
		ObjectMapper objectMapper = new ObjectMapper();
		ShoppingCartVo[] arr = null;
		try {
			arr = objectMapper.readValue(orderList, ShoppingCartVo[].class);
	    } catch (JsonParseException e) {
	        e.printStackTrace();
	    } catch (JsonMappingException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
		if(arr[0].getShoppingCartId() != 0){
			ShoppingCart shoppingCart = shoppingCartService.selectShoppingCartByShoppingCartId(arr[0].getShoppingCartId());
			shoppingCart.setIsDelete("-1");
			shoppingCartService.updateShoppingCart(shoppingCart);
		}
		
		boolean b = false;
		boolean c = true;
		Order order = new Order();
		
		/*Integer isFree = 0;
		if(arr[0].getProMealPrice() == 0.0) isFree = 1;
		order.setIsFree(isFree);*/
		order.setOccurTime(new Date());
		/*order.setOrderMoney(arr[0].getProMealPrice());*/
		order.setOrderNum(orderNum);//订单编号
		//order.setOrderState(isPay);//1待付款,0已付款
		order.setCount(1);
		order.setMealId(arr[0].getProMealId());
		order.setBuyType(0);//0新购，1续费
		order.setParentId(user.getUserId());
		order.setPayWayId(2);
		
		if(Integer.valueOf(productId) == 0) {
			//套餐
			List<MealProduct> mpList =  mealProductService.selectMealProductsByMealId(arr[0].getProMealId());
			String productIds = "";//重组后为 "1|2|3|4|5"
			for(int j=0;j<mpList.size();j++){
				int p_idx = mpList.get(j).getProductId();
				productIds += String.valueOf(p_idx);
				if(j<mpList.size()-1)
				productIds = productIds + "|";
			}
			order.setProIds(productIds);  //套餐内的产品id
			order.setUseLife(arr[0].getUseLife());
			order.setUserNum(arr[0].getUserNum());
			
			//到期时间
			Date overTime = null;
			if(arr[0].getUseLife().equals("0")) {
				order.setOrderState("0");
				order.setPayTime(new Date());
				
				order.setPayMoney(0.00);
				order.setOrderMoney(0.00);
				order.setPayByAccount(0.00);
				order.setPayByOther(0.00);
				
				overTime = SignUtil.getOvertime(5, +20,new Date());
				order.setOverTime(overTime);
				order.setProOverTime(overTime);
				
				//价格计算
				order.setIsFree(1);
				order.setOrderMoney(0.00);
				order.setOrderState("0");//1待付款,0已付款
				
				arr[0].setPrice(0.00);
			}else {
				order.setOrderState("1");
				//价格计算
				order.setIsFree(0);
				MealFee mf = mealFeeService.selectMealFeeByMealId(arr[0].getProMealId());
				Integer mfUseYear = mf.getUserYear();
				if(mfUseYear == -1) {
					mfUseYear = 1;
				}
				
				String useLife = arr[0].getUseLife();
				if(useLife.equals("-1")) {
					useLife = "1";
					overTime = SignUtil.getOvertime(1, +80,new Date());
				}else {
					overTime = SignUtil.getOvertime(1, +Integer.valueOf(arr[0].getUseLife()),new Date());
				}
				
				order.setOverTime(overTime);
				order.setProOverTime(overTime);
				
				Double mealPrice = (mf.getPrice()/mfUseYear/mf.getUserNum())*Integer.valueOf(useLife)*arr[0].getUserNum();
				order.setOrderMoney(mealPrice);
				
				arr[0].setPrice(mealPrice/mfUseYear/arr[0].getUserNum());
			}
			
		}else {
			
			//=================================================================================================================
			
			//根据套餐Id和用户Id查找最近一条订单记录
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("mealId", arr[0].getProMealId());
			map.put("userId", arr[0].getUserId());
			map.put("sortField", "pay_time");
			map.put("sortOrder", "desc");
			
			Order entity = orderService.selectOrderByMealIdAndProductId(map);
			order.setProIds(entity.getProIds());
			order.setNewProId(Integer.valueOf(productId));
			
			order.setUseLife(entity.getUseLife());
			order.setUserNum(entity.getUserNum());
			order.setOverTime(entity.getOverTime());
//			order.setDataExtend(arr[0].getUseLife()+"&"+arr[0].getUserNum()+"&"+SignUtil.time2str(SignUtil.getOvertime(1, +arr[0].getUseLife()), "yyyy-MM-dd"));
			
			String orderUseLife = entity.getUseLife();
			Integer orderUserNum = entity.getUserNum();
			
			String arrUseLife = arr[0].getUseLife();
			Integer arrUserNum = arr[0].getUserNum();
			
			Double proPrice = 0.00;
			Integer userNum = 0;
			String _toDate = "";
			
			//人数计算
			if(arrUserNum > orderUserNum){
				userNum = orderUserNum;
			}else{
				userNum = arrUserNum;
			}
			arr[0].setUserNum(userNum);
			
			//产品到期时间
			Date proOverTime = entity.getOverTime();
			//产品的扩展字段
			String dataExtend = arr[0].getUseLife()+"&"+arr[0].getUserNum()+"&"+SignUtil.time2str(entity.getOverTime(), "yyyy-MM-dd");
			
			//试用   年限及价格计算
			if(arrUseLife.equals("20天") || "0".equals(isPay)){
				proPrice = 0.00;
				_toDate = DateUtil.getMonth("getOverTime", new Date(),entity.getOverTime());
				Integer _day = DateUtil.getDateAndTodayDiffer(new java.sql.Date(entity.getOverTime().getTime()));
				if(_day <= 20){
					arr[0].setUseLife(_toDate);
					arr[0].setPrice(0.00);
				}else{
					arr[0].setUseLife("20天");
					arr[0].setPrice(0.00);
				}
				order.setProIds(entity.getProIds()+"|"+productId);
				order.setOrderState("0");
				order.setPayTime(new Date());
				order.setIsFree(1);
				order.setOrderMoney(0.00);
				order.setPayMoney(0.00);
				order.setPayByAccount(0.00);
				order.setPayByOther(0.00);
				
			}else{
//				=================================================
				//购买   年限及价格计算
				order.setIsFree(0);
				order.setOrderState("1");
				ProductFee pf = productFeeService.selectProductFeeByProductId(Integer.valueOf(productId));
				
				if(orderUseLife.equals("0")){
					_toDate = DateUtil.getMonth("getOverTime", new Date(),entity.getOverTime());
					Integer _day = DateUtil.getDateAndTodayDiffer(new java.sql.Date(entity.getOverTime().getTime()));
					if(_day <= 20){
						arr[0].setUseLife(_toDate);
						proPrice = 0.00;
						arr[0].setPrice(0.00);
					}else{
						arr[0].setUseLife("20天");
						proPrice = 0.00;
						arr[0].setPrice(0.00);
					}
				}else {
					//arrUserLife的值为‘2年’或‘2年2月2天’ 如何计算截止日期 ======================
					
					//计算所选择的截止日期
					Date endTime = arr[0].getEndTime();
					//还有多长时间到期  年月日
					_toDate = DateUtil.getMonth("getOverTime", new Date(),entity.getOverTime());
					Integer _month = Integer.valueOf(DateUtil.getMonth("getMonth", new Date(),entity.getOverTime()));
					
					if(endTime.getTime() <= entity.getOverTime().getTime()){
						arr[0].setUseLife(arrUseLife);
						Integer aul = Integer.valueOf(DateUtil.getMonth("getMonth", new Date(),endTime));
						proPrice = pf.getProductPrice()/pf.getUserNum()/pf.getUseYear()/12*aul*arr[0].getUserNum();
						arr[0].setPrice(pf.getProductPrice()/pf.getUserNum()/pf.getUseYear());
						dataExtend = arr[0].getUseLife()+"&"+arr[0].getUserNum()+"&"+SignUtil.time2str(endTime, "yyyy-MM-dd");
						proOverTime = endTime;
					}else{
						arr[0].setUseLife(_toDate);
						proPrice = pf.getProductPrice()/pf.getUserNum()/pf.getUseYear()/12*_month*arr[0].getUserNum();
						arr[0].setPrice(pf.getProductPrice()/pf.getUserNum()/pf.getUseYear());
					}
					
				}
			}
			order.setDataExtend(dataExtend);
			order.setProOverTime(proOverTime);
			arr[0].setProMealPrice(proPrice);
			order.setOrderMoney(proPrice);
		}
		
		order.setUserId(arr[0].getUserId());
		order.setIsDredge(0);//0失败  1成功
		
		try {
			b = orderService.insertOrder(order);
		} catch (Exception e) {
			b = false;
		}
		
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>)request.getSession().getAttribute("cartInfo");
		
		request.getSession().setAttribute("cartInfo",map);
		
		if(Integer.valueOf(isPay) == 0){
//		if(arr[0].getUseLife() == 0){
			//新增一条交易记录
			Deal deal = new Deal();
			deal.setDealDate(new Date());
			deal.setDealName(arr[0].getProMealName());
			deal.setDealNum(order.getOrderNum());
			deal.setDealState("2");
			deal.setDisburseMoney(order.getOrderMoney());
			deal.setIncomeMoney(0.0);
			deal.setPayWayId(2);
			deal.setUserId(arr[0].getUserId());
			deal.setParentId(user.getUserId());
			
			try {
				c = dealService.insertDeal(deal);
			} catch (Exception e) {
				c = false;
			}
			
			//=============================收支明细增加======================================
			//交易收支明细
			Cashflow cashflow = new Cashflow();
			cashflow.setCashflowNum(createNum.createCashflowNum("2"));
			cashflow.setCreateTime(new Date());
			cashflow.setDealType(2);
			cashflow.setDisburseMoney(0.00);
			cashflow.setIncomeMoney(0.00);
			cashflow.setOrderId(order.getOrderId());
			cashflow.setPayWayId(2);
			cashflow.setThenAccount(user.getAccountMoney());
			cashflow.setUserId(user.getUserId());
			cashflow.setIsCancel(0);
			cashflowService.insertCashflow(cashflow);
			//============================================================================
			
			if(Integer.valueOf(productId) == 0) {
				//========================普元同步开始<套餐>====================================//
//				Order order = orderService.selectOrderByOrderId(714);
				//User user = userService.selectUserInfoByUserId(order.getUserId());
				if(order.getMealId() != 3) {
					EOSresult = eos.sendMeal(order.getOrderId());
				}
				//========================普元同步结束<套餐>====================================//
			}else{
				//========================普元同步开始<产品>====================================//
				EOSresult = eos.sendProduct(order.getOrderId());
				//========================普元同步结束<产品>====================================//
			}
			
			if("ok".equals(EOSresult)) {
				//激活新用户
				User newUser = userService.selectUserInfoByUserId(order.getUserId());
				newUser.setIsLive("1");
				userService.updateUserByKey(newUser);
				
				//更改订单的开通状态
				Order updateOrder = orderService.selectOrderByOrderId(order.getOrderId());
				updateOrder.setIsDredge(1);//0失败  1成功
				orderService.updateOrderByOrderId(updateOrder);
			}
		}
		
		request.getSession().setAttribute("order", order);
		request.getSession().setAttribute("userInfo", user);
		request.getSession().setAttribute("proMealName", arr[0].getProMealName());
		request.getSession().setAttribute("EOSresult", EOSresult);
		request.getSession().setAttribute("BSTCOMPANYINFO", readProperties);
		
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("orderMoney", order.getOrderMoney());
		
		if(b && c)
			//return true;
			map2.put("isSuccess", true);
		else 
			//return false;
			map2.put("isSuccess", false);
		
		return map2;
	}
	
	/**
	 * @return 验证代金券是否有效及代金券的金额
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkVoucherNum", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkVoucherNum(String voucherNum) throws Exception {
		
		Voucher voucher = voucherService.selectVoucherByVoucherNum(voucherNum);
		
		Map<String, Object> map = new HashMap<String, Object>();
		if(voucher == null){
			map.put("success", false);
		} else{
			map.put("success", true);
			map.put("voucher",voucher);
		}
		
		return map;
	}
	
	/**
	 * @return 提交订单并支付页面 
	 * @throws Exception
	 */
	@RequestMapping(value = "/submitOrders", method = RequestMethod.GET)
	public ModelAndView submitOrders(HttpServletRequest request) throws Exception {
		
		Order order = (Order) request.getSession().getAttribute("order");
		User user =  (User) request.getSession().getAttribute("userInfo");
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("buy/submit-orders");
		modelAndView.addObject("order", order);
		modelAndView.addObject("userInfo", user);
		
		return modelAndView;
	}
	
	/**
	 * @return 待付款到支付页面 
	 * @throws Exception
	 */
	@RequestMapping(value = "/obligationToPay", method = RequestMethod.GET)
	public ModelAndView obligationToPay(HttpServletRequest request) throws Exception {
		Integer orderId = Integer.valueOf(request.getParameter("orderId"));
		Order order = orderService.selectOrderByOrderId(orderId);
		String proMealName = "";
		String productId = "0";
		if(order.getNewProId() != null) {
			Product product = productService.selectProductByProductId(order.getNewProId());
			proMealName = product.getProductName();
			productId = String.valueOf(product.getProductId());
		}else {
			Meal meal = mealService.selectMealByMealId(order.getMealId());
			proMealName = meal.getMealName();
			productId = "0";
		}
		User user =  (User) request.getSession().getAttribute("userInfo");
		request.getSession().setAttribute("productId",productId);
		request.getSession().setAttribute("order",order);
		
		ModelAndView modelAndView = new ModelAndView();
		
		modelAndView.addObject("order", order);
		modelAndView.addObject("userInfo", user);
		modelAndView.addObject("proMealName", proMealName);
		modelAndView.setViewName("buy/submit-orders");
		
		return modelAndView;
	}
	
	/**
	 * 支付
	 * @param orderId
	 * @param orderMoney
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/payOrder/{orderId}/{orderMoney}/{proMealName}/{voucher}", method = RequestMethod.GET)
	public ModelAndView payOrder(@PathVariable Integer orderId,@PathVariable Double orderMoney,@PathVariable String proMealName,
			@PathVariable String voucher,HttpServletRequest request) throws Exception {
		Order order = orderService.selectOrderByOrderId(orderId);
		double voucherMoney = 0.00;
		if(!"0".equals(voucher)) {
			voucherMoney = voucherService.selectVoucherByVoucherNum(voucher).getVoucherMoney();
		}
		
		User user = (User)request.getSession().getAttribute("userInfo");
		Double accountMoney = user.getAccountMoney()-order.getOrderMoney()-voucherMoney;
		Double invoiceMoney = user.getInvoiceMoney() + order.getOrderMoney();
/*		Double accountMoney = user.getAccountMoney()-orderMoney;
		Double invoiceMoney = user.getInvoiceMoney() + orderMoney;
*/		String EOSresult = null;
		//账户余额更新
		user.setAccountMoney(accountMoney);
		user.setInvoiceMoney(invoiceMoney);
		userService.updateUserByKey(user);
		
		request.getSession().setAttribute("userInfo", user);
		String productId = (String)request.getSession().getAttribute("productId");
		
		//订单状态修改
		if(order.getBuyType() == 0) {
			if(Integer.valueOf(productId) != 0) {
				if(SignUtil.isNotEmpty(String.valueOf(order.getNewProId()))) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("mealId", order.getMealId());
					map.put("userId", order.getUserId());
					map.put("sortField", "pay_time");
					map.put("sortOrder", "desc");
					Order entity = orderService.selectOrderByMealIdAndProductId(map);
					
					order.setProIds(entity.getProIds()+"|"+order.getNewProId());
				}
			}
		}
		
		order.setPayMoney(order.getOrderMoney()-voucherMoney);
		order.setPayByAccount(order.getOrderMoney()-voucherMoney);
		order.setPayByOther(0.00);
		order.setOrderState("0");
		order.setPayTime(new Date());
		order.setPayWayId(2);
		
		orderService.updateOrderByOrderId(order);
		request.getSession().setAttribute("order", order);
		
		
		//增加交易信息
		Deal deal = new Deal();
		deal.setDealDate(new Date());
		deal.setDealName(proMealName);
		deal.setDealNum(order.getOrderNum());
		deal.setDealState("2");
		deal.setDisburseMoney(order.getOrderMoney()-voucherMoney);
		deal.setIncomeMoney(0.0);
		deal.setPayWayId(2);
		deal.setUserId(order.getUserId());
		deal.setParentId(user.getUserId());
		
		dealService.insertDeal(deal);
		
		//=============================收支明细增加======================================
		//交易收支明细
		Cashflow cashflow = new Cashflow();
		cashflow.setCashflowNum(createNum.createCashflowNum("2"));
		cashflow.setCreateTime(new Date());
		cashflow.setDealType(2);
		cashflow.setDisburseMoney(order.getOrderMoney()-voucherMoney);
		cashflow.setIncomeMoney(0.00);
		cashflow.setOrderId(order.getOrderId());
		cashflow.setPayWayId(2);
		cashflow.setThenAccount(user.getAccountMoney());
		cashflow.setUserId(user.getUserId());
		cashflow.setIsCancel(0);
		cashflowService.insertCashflow(cashflow);
		//============================================================================
		
		if(order.getBuyType() == 0) {
			if(Integer.valueOf(productId) == 0) {
				//========================普元同步开始<套餐>====================================//
				if(order.getMealId() != 3) {
					EOSresult = eos.sendMeal(order.getOrderId());
				}
				//========================普元同步结束<套餐>====================================//
			}else{
				//========================普元同步开始<产品>====================================//
				EOSresult = eos.sendProduct(order.getOrderId());
				//========================普元同步结束<产品>====================================//
			}
		}else {
			if(order.getMealId() != 3) {
				EOSresult = eos.sendProOrMeal(order.getOrderId());
			}
		}
		
		if("ok".equals(EOSresult)) {
			if(order.getBuyType() == 0) {
				//激活新用户
				User newUser = userService.selectUserInfoByUserId(order.getUserId());
				newUser.setIsLive("1");
				userService.updateUserByKey(newUser);
			}
			
			//更改订单的开通状态
			Order updateOrder = orderService.selectOrderByOrderId(order.getOrderId());
			updateOrder.setIsDredge(1);//0失败  1成功
			orderService.updateOrderByOrderId(updateOrder);
		}
		
		request.getSession().setAttribute("EOSresult", EOSresult);
		
		return new ModelAndView("redirect:/buy/successOrder");
	}
	
	/**
	 * @return 成功页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/successOrder", method = RequestMethod.GET)
	public ModelAndView successOrder(HttpServletRequest request) throws Exception {
		
		String EOSresult = (String) request.getSession().getAttribute("EOSresult");
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("payWayName", "账户余额支付");
		modelAndView.addObject("EOSresult", EOSresult);
		Order order = (Order) request.getSession().getAttribute("order");
		modelAndView.addObject("order", order);
		if(order.getBuyType() == 0) {
			modelAndView.setViewName("buy/success-order_byaccount");
		}else {
			modelAndView.setViewName("users/myservice/uporders_success");
		}
		return modelAndView;
	}
	
	/**
	 * 两种方式支付
	 * @param orderId
	 * @param orderMoney
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/payOrderByTwo/{orderId}/{payByAccountMoney}/{payByOther}/{proMealName}/{voucher}", method = RequestMethod.GET)
	public ModelAndView payOrderByTwo(@PathVariable Integer orderId,@PathVariable Double payByAccountMoney,
			@PathVariable Double payByOther,@PathVariable String proMealName,@PathVariable String voucher,
			HttpServletRequest request) throws Exception {
		User user = (User)request.getSession().getAttribute("userInfo");
		Double accountMoney = user.getAccountMoney()-payByAccountMoney;
		Double invoiceMoney = user.getInvoiceMoney() + payByAccountMoney;
		//账户余额更新
		user.setAccountMoney(accountMoney);
		user.setInvoiceMoney(invoiceMoney);
		userService.updateUserByKey(user);
		
		request.getSession().setAttribute("userInfo", user);
		
		//修改代金券状态
		if(!voucher.equals(0)){
			Voucher v = voucherService.selectVoucherByVoucherNum(voucher);
			v.setState(1);
			voucherService.updateVoucherState(v);
		}
		
		//查询订单信息
		Order order = orderService.selectOrderByOrderId(orderId);
		
		return new ModelAndView("redirect:/alipay/doPay?orderNum="+order.getOrderNum()+"&orderMoney="+payByOther+"&userId="+order.getUserId()+"&proMealName="+proMealName+"&orderId="+orderId);
		
	}

	/**
	 * @return 发送邮件给客户  以及本公司
	 * @throws Exception
	 */
	@RequestMapping(value = "/orderSendEmailToUser", method = RequestMethod.POST)
	@ResponseBody
	public Boolean orderSendEmailToUser(String orderLinkEmail,String loginUserUnitAllName,String orderLinkMan,String orderLinkPhone,
			String proMealName,Integer orderId,String voucherNum,HttpServletRequest request ) throws Exception {
		
		boolean a = false;
		boolean b = false;
		boolean c = false;
		boolean e = false;
		
		User user = (User) request.getSession().getAttribute("userInfo");
		String userInfoName = "";
		if(user.getUserEmail() == "" || "".equals(user.getUserEmail())){
			userInfoName = user.getUserTel();
		}else{
			userInfoName = user.getUserEmail();
		}
		
		Order order = orderService.selectOrderByOrderId(orderId);
		order.setPayWayId(4);
		
		Double orderMoney = order.getOrderMoney();
		if(!"0".equals(voucherNum)){
			
			Voucher voucher = voucherService.selectVoucherByVoucherNum(voucherNum);
			voucher.setState(1);
			voucherService.updateVoucherState(voucher);
			
			order.setVoucherNum(voucherNum);
			orderMoney = orderMoney - voucher.getVoucherMoney();
		}
		
		a = orderService.updateOrderByOrderId(order);
		
		//给客户发邮件  {"用户名","套餐名","注册账号","订单编号","产品名称","实付金额","付款单位全称","付款单位联系人","付款单位联系电话", "收款单位全称","收款单位开户行","收款单位账号","收款单位服务电话"}
		b = EmailUtil.sendMailBuyOutline(orderLinkEmail,new String[]{userInfoName,proMealName,userInfoName,order.getOrderNum(),proMealName,orderMoney.toString(),loginUserUnitAllName,orderLinkMan,orderLinkPhone,readProperties.getBstCompanyName(),readProperties.getBstBankNname(),readProperties.getBstAccount(),readProperties.getBstServiceTel()});
		
		//公司发邮件       {"客户邮箱","注册账号","订单编号","产品名称","实付金额","付款单位全称","付款单位联系人","付款单位联系电话","收款单位全称", "收款单位开户行","收款单位账号","收款单位服务电话"}
		c = EmailUtil.sendMailBSTNewOrder(readProperties.getBstCWEmail(),new String[]{orderLinkEmail,userInfoName,order.getOrderNum(),proMealName,orderMoney.toString(),loginUserUnitAllName,orderLinkMan,orderLinkPhone,readProperties.getBstCompanyName(),readProperties.getBstBankNname(),readProperties.getBstAccount(),readProperties.getBstServiceTel()});
		
		//新增线下支付记录
		Payment payment = new Payment();
		payment.setPaymentNum(createNum.createPaymentNum("2"));
		payment.setUserId(user.getUserId());
		payment.setAttachIds("");
		payment.setCreateTime(new Date());
		payment.setDealType(2);
		payment.setLinkMan(orderLinkMan);
		payment.setLinkTell(orderLinkPhone);
		payment.setOrderId(orderId);
		payment.setPaymentState(0);
		payment.setRemitMoney(orderMoney);
		payment.setRemitCompany(loginUserUnitAllName);
		
		e = paymentService.insertPayment(payment);
		
		if(a && b && c && e){
			return true;
		} else{
			return false;
		}
	}

	/**
	 * @return 添加
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value="/haveMealsNum",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> haveMealsNum(HttpServletRequest request){
		User user = (User)request.getSession().getAttribute("userInfo");
		
		Map<String, Object> _map = new HashMap<String, Object>();
		_map.put("userId",user.getUserId());
		_map.put("isYun",user.getIsYun());
		_map.put("isYun",user.getIsYun());
		
		List<OrderVo> orderVoList = orderService.selectMealsNumByCondition(_map);
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("orderVoList",orderVoList);
		request.getSession().setAttribute("userMealInfo", orderVoList);
		return map;
	}
	
	
	/**
	 * @return 升级产品订单页面
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value = "/upOrders", method = RequestMethod.GET)
	public ModelAndView upOrders(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("buy/uporders");
		return modelAndView;
	}
	
	
	public static void main(String[] args) {
		System.out.println(1/3*3);
	}
}


